package structure;

import java.util.Arrays;

public class MyStack {
    public static void main(String[] args) {
        MyStack stack = new MyStack();
        stack.push(1);
        stack.push(2);
        stack.push(3);
        stack.push(4);
        System.out.println("栈的有效长度为:" + stack.size());
        int a = stack.peek();
        System.out.println(a);
        //出栈(删除)
        int b = stack.pop();
        System.out.println(b);
        //判断是否为空栈
        boolean n = stack.empty();
        System.out.println(n);
        stack.display();
    }
    private int[] elem;
    private int usedSize;
    private static final int DEFAULT_SIZE = 10;
    public MyStack(){
        elem = new int[10];
    }
    public int size(){
        return usedSize;
    }
    public void push(int num){
        if(full()){
            grow();
        }
        elem[usedSize] = num;
        usedSize++;
    }
    public int pop(){
        if(empty()){
            throw new StackEmptyException("栈为空异常!");
        }
        usedSize--;
        return elem[usedSize];
    }
    public int peek(){
        if(empty()){
            throw new StackEmptyException("栈为空异常!");
        }
        return elem[usedSize - 1];
    }
    public void grow(){
        elem = Arrays.copyOf(elem,elem.length * 2);
    }
    public boolean full(){
        if(usedSize == DEFAULT_SIZE){
            return true;
        }
        return false;
    }
    public boolean empty(){
        if(usedSize == 0){
            return true;
        }
        return false;
    }
    public void display(){
        if(empty()){
            throw new StackEmptyException("栈为空异常!");
        }
        System.out.print("[");
        for(int i = 0;i < usedSize;i++){
            System.out.print(elem[i]);
            if(i != usedSize - 1){
                System.out.print(", ");
            }
        }
        System.out.println("]");
    }
}
